package br.com.salao.ejb.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import br.com.salao.ejb.dao.LoginDao;
import br.com.salao.entity.Login;

public class LoginDaoImpl implements LoginDao{
	
	private final GenericDao<Login> dao;
	private Logger logger = Logger.getLogger(LoginDaoImpl.class.getName());
	private EntityManager em;
	
	public LoginDaoImpl(EntityManager em){
		this.em = em;
		dao = new GenericDao<Login>(em, Login.class);
	}
	
	public Login inserir(Login login){
		logger.debug(":: LoginDaoImpl :: inserir () :: login " + login.getLogin());
		return dao.salvar(login);
	}
	
	public Login buscarLoginPorDescricao(String login){
		
		logger.debug(":: LoginDaoImpl :: buscarLoginPorDescricao () :: login " + login);
		
		Login loginBD = null;
		
		try {		
			Query query = em.createQuery("from Login l where l.login like :login");
			query.setParameter("login", login);			
			loginBD = (Login) query.getSingleResult();
			
		} catch (Exception e) {
			logger.error(" :: LoginDaoImpl :: buscarLoginPorDescricao() :: Login: [" + login + "]" + e.getCause());
			//e.printStackTrace();
			loginBD = null;
		} 
		return loginBD;		
	}
	
	public Login buscarLoginPorId(int id){
		
		Login loginBD = null;
		logger.debug(":: LoginDaoImpl :: buscarLoginPorId () ::" );
				
		try {		
			Query query = em.createQuery("from Login l where l.id = :id");
			query.setParameter("id", id);			
			loginBD = (Login) query.getSingleResult();
			
		} catch (Exception e) {
			logger.error(":: buscarLoginPorId() :: ID Login: [" + id + "]" + e.getCause());
			loginBD = null;
		}
		return loginBD;		
	}

	public Login update(Login login) {
		return dao.update(login);
	}
	
	public Login findLoginByCPF(String cpf){		

		Login objLogin ;

		try{
			Query query = em.createQuery("from Login l where l.cpf =:cpf");
			query.setParameter("cpf", cpf);
			objLogin = (Login)query.getSingleResult();
		}catch (Exception e) {
			logger.error(":: findLoginByCPF() ::  CPF: [" + cpf + "]" + e.getCause());
			return null;
		}
		return objLogin; 
	}
}
